'use strict';

const Sequelize = require('sequelize');
const Service = require('egg').Service;
const Op = Sequelize.Op;

class AdminService extends Service {
  // 添加订单
  async create(dataObj) {
    const { ctx, service } = this;
    const { Order, Goods, GoodsPhoto } = this.app.model.Tables.Shop;
    const { Admin } = this.app.model.Tables.Com;
    try {
      const idArr = [];
      const obj = {};

      // 提取出前端传来的商品id和数量
      dataObj.goods_info.forEach((el) => {
        idArr.push(el.id);
        obj[el.id] = el.num;
      });

      // console.log(obj, 'obj');

      // 查找传来商品id组的商品信息，链表商家信息
      let resultGoods = await Goods.findAll({
        where: {
          id: idArr,
        },
        attributes: [
          'id',
          ['name', 'goods_name'],
          'stock_num',
          'price',
          'sale_price',
          'sold_num',
          'desc',
        ],
        include: [
          {
            // 需要的字段
            attributes: ['id', 'name'],
            // 链接的表
            model: Admin,
          },
          {
            // 需要的字段
            attributes: ['id', 'path'],
            model: GoodsPhoto,
            where: {
              type: 1,
            },
          },
        ],
      });

      // 商品添加已销售数量 + 1
      let j = 0;
      while (resultGoods[j]) {
        const good = resultGoods[j] && resultGoods[j].dataValues;
        //  判断商品数量是否超过了库存数量
        if (good.stock_num < obj[good.id]) {
          return {
            code: 1,
            msg: '库存不足',
            data: {
              good_id: good.id,
              good_name: good.goods_name,
              stock_num: good.stock_num,
            },
          };
        }
        await resultGoods[j].update({
          sold_num: Number(good.sold_num) + Number(obj[good.id]),
          stock_num: good.stock_num - obj[good.id],
        });
        j++;
      }

      let total_price = 0;
      let shops_name = '';
      let shops_id = '';
      // 重新拼接对象
      resultGoods = resultGoods.map((el) => {
        // 存在优惠价，就计算优惠价
        total_price += (el.sale_price ? el.sale_price : el.price) * obj[el.id];
        el.dataValues.num = obj[el.id];
        if (!shops_name) {
          shops_name =
            (el.s_admin &&
              el.s_admin.dataValues &&
              el.s_admin.dataValues.name) ||
            '';
        }
        if (!shops_id) {
          shops_id =
            (el.s_admin && el.s_admin.dataValues && el.s_admin.dataValues.id) ||
            0;
        }

        return el;
      });

      const dataObjNew = {
        // 订单id
        order_id: Date.now() + Math.floor(Math.random() * 9000 + 1000),
        // 商品组信息
        goods_info: JSON.stringify(resultGoods),
        user_id: ctx.userInfo.id,
        project_id: ctx.userInfo.project_id,
        order_time: Date.now(),
        // 总价格
        total_price,
        addr_id: dataObj.addr_id,
        shops_name,
        shops_id,
      };

      const result = await Order.create(dataObjNew);
      // 如果是购物车结算的，有传购物车单条信息id，则清除购物车该条信息
      const carIds = dataObj.shoppingCartIds;

      if (carIds) {
        for (let index = 0; index < carIds.length; index++) {
          const element = carIds[index];
          await service.shop.shoppingCart.destroy(element);
        }
      }

      return result
        ? ctx.response.success('添加成功', result)
        : ctx.response.error(result, '添加失败');
    } catch (error) {
      return ctx.response.error(error.message);
    }
  }
  // 获取订单列表
  async index() {
    const { ctx } = this;
    try {
      const { Order } = this.app.model.Tables.Shop;
      const query = this.ctx.query;
      // 每页多少条
      const limit = parseInt(query.limit) || 10;
      // 页数
      const page = parseInt(query.page) || 1;
      // 页数 * 每页个数
      const offset = limit * (page - 1);
      const str_status = ctx.query.status; //获取前端传过来的状态码
      //对状态码进行处理
      let arr_status;
      if (str_status == undefined || str_status == '') {
        arr_status = null;
        //如果前端没有传或者传递一个空的status
        //就默认显示所有状态的商品
      } else {
        arr_status = str_status;
        //前端传了状态码，只显示对应状态码的商品
      }
      const default_start = '1970-01-01';
      const default_end = '9999-12-31';
      const start = this.ctx.query.start || default_start;
      const end = this.ctx.query.end || default_end;
      const where = {
        project_id:
          query.project_id ||
          this.ctx.userInfo.project_id ||
          this.ctx.adminInfo.project_id,
        status:
          arr_status !== null
            ? arr_status
            : {
                [Op.or]: [
                  -1,
                  0,
                  1,
                  2,
                  3,
                  4,
                  5,
                  6,
                  7,
                  '1',
                  '2',
                  '3',
                  '4',
                  '5',
                  '6',
                  '7',
                ],
              },
        createdAt: {
          [Op.between]: [start, end],
        },
      };

      query.order_id && (where.order_id = { [Op.like]: `%${query.order_id}%` });
      if (!where.project_id) return this.ctx.response.lack('project_id');

      if (!ctx.adminInfo)
        where.user_id =
          (ctx.query && ctx.query.id) ||
          (ctx.adminInfo && ctx.adminInfo.id) ||
          (ctx.userInfo && ctx.userInfo.id);

      const result = await Order.findAndCountAll({
        limit,
        offset,
        order: [['createdAt', 'DESC']],
        where,
      });

      //查询到的订单列表存到数组中
      let order_list = result.rows;

      //遍历数组判断是否过期
      order_list.map((ele) => {
        let differTime = Date.now() - ele.order_time; //现在的时间戳-订单创建的时间戳
        let outTime = 30 * 60 * 1000; //过期时间 30min

        if (ele.status === '1' && differTime > outTime) {
          console.log(
            '--------------------------------------------------------------------------------'
          );
          console.log('This Product Is Out Of Date');
          console.log(Date.now(), ele.order_time);
          console.log(differTime, outTime);
          ele.status = '0'; //如果过期则状态码为-1
          this.update(ele.id, { status: ele.status });
        }
      });

      if (result) {
        return this.ctx.response.success(result, '获取成功');
      }
      return this.ctx.response.error('获得订单列表信息失败');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  // 获取七天内的已支付订单笔数
  async ordercount() {
    try {
      const { Order } = this.app.model.Tables.Shop;
      const query = this.ctx.query;
      // 每页多少条
      const limit = parseInt(query.limit) || 10;
      // 页数
      const page = parseInt(query.page) || 1;
      // 页数 * 每页个数
      const offset = limit * (page - 1);
      let orderlist = [];
      for (let i = 1; i < 8; i++) {
        let after_time = Date.now() + 24 * 3600 * 1000;
        let after = new Date(after_time).toISOString();
        let before_time = after_time - i * (24 * 3600 * 1000);
        let before = new Date(before_time).toISOString();
        let start = before;
        let end = after;
        const where = {
          status: '2',
          createdAt: {
            [Op.between]: [start, end],
          },
          project_id: query.project_id,
        };
        const result = await Order.findAll({
          limit,
          offset,
          where,
          distinct: true,
        });
        let order_total = result.length;
        let dataobj = {
          date: before,
          num: order_total,
        };
        orderlist.push(dataobj);
      }

      return this.ctx.response.success(orderlist, '获取成功');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }

  // 获取单个订单信息
  async show(id) {
    try {
      const { Order, Address, User } = this.app.model.Tables.Shop;
      const result = await Order.findOne({
        where: {
          id,
          //   user_id: this.ctx.adminInfo.id,
        },
        include: [
          {
            // 需要的字段
            // attributes: [ 'id', 'path' ],
            // 链接的表
            model: Address,
          },
        ],
      });

      if (result) {
        let differTime = Date.now() - result.order_time;
        let outTime = 30 * 60 * 1000;
        if (result.status === '1' && differTime > outTime) {
          result.status = '0';
          this.update(id, { status: result.status });
        }

        const data = JSON.parse(JSON.stringify(result));
        data.goods_info = JSON.parse(data.goods_info);
        data.goods_info.map((rg) => {
          return rg;
        });
        return this.ctx.response.success(data);
      }
      return this.ctx.response.error('找不到该订单信息');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  // 更新订单信息
  async update(id, data) {
    const { ctx } = this;

    try {
      const { Order } = this.app.model.Tables.Shop;
      const resultGoods = await Order.findOne({
        where: {
          id,
        },
      });

      if (resultGoods) {
        const resultG = await resultGoods.update(data);
        return resultG;
      }
      return ctx.response.error('找不到该订单信息');
    } catch (error) {
      return ctx.response.error(error.message);
    }
  }

  getByOrderId(order_id) {
    const { Order } = this.app.model.Tables.Shop;

    return Order.findOne({
      where: {
        order_id,
      },
    });
  }

  async updateByOrderId(order_id, data) {
    const { ctx } = this;
    try {
      const { Order } = this.app.model.Tables.Shop;
      const resultGoods = await Order.findOne({
        where: {
          order_id,
        },
      });

      if (resultGoods) {
        const resultG = await resultGoods.update(data);
        console.log(resultG);
        return resultG;
      }
      return ctx.response.error('找不到该订单信息');
    } catch (error) {
      console.log(error);
      return ctx.response.error(error.message);
    }
  }

  // 删除订单
  async destroy(id) {
    const { ctx } = this;
    try {
      const { ctx } = this;
      const { Order, Address, User } = this.app.model.Tables.Shop;
      const result = await Order.destroy({
        where: {
          id,
          //   user_id: ctx.adminInfo.id,
        },
      });
      return result > 0
        ? ctx.response.success('删除成功')
        : ctx.response.error('删除失败');
    } catch (error) {
      return ctx.response.error(error.message);
    }
  }
  //创建物流信息
  async createLogistics() {
    const { app, ctx } = this;
    const { Order, Address, Logistics, User } = app.model.Tables.Shop;
    const data = ctx.request.body;
    //获取token
    const token = ctx.get('authorization');
    let isOrder = await Logistics.findOne({
      where: {
        order_id: data.order_id,
      },
    });
    //转时间格式
    function getTiming(timeing) {
      let date = new Date(Number(timeing));
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      let hour = date.getHours();
      let minute = date.getMinutes();
      let second = date.getSeconds();

      day = day < 10 ? String(day).padStart(2, '0') : day;
      hour = hour < 10 ? String(hour).padStart(2, '0') : hour;
      minute = minute < 10 ? String(minute).padStart(2, '0') : minute;

      return `${year}.${month}.${day} ${hour}:${minute}:${second}`;
    }
    //如果有物流信息 判断长度是否大于6 不大于6则修改物流信息
    if (isOrder) {
      let content = JSON.parse(isOrder.dataValues.content);
      if (content.length >= 6) {
        return '已存在物流信息';
      } else {
        //获取物流信息
        let logistics = await ctx.curl(
          'http://www.kuaidi.com/index-ajaxselectcourierinfo--.html'
        );
        let res = JSON.parse(logistics.data);
        //查找下单的用户
        let userRes = await User.findOne({
          where: {
            token: token,
          },
        });
        // console.log(userRes);
        //查找订单信息
        let findRes = await Order.findOne({
          where: {
            order_id: data.order_id,
          },
          include: [
            {
              model: Address,
            },
          ],
        });
        // console.log(findRes);
        //格式化时间
        let time = Number(findRes.dataValues.order_time);
        let timeArr = [];
        for (let i = 0; i < 30; i++) {
          timeArr.push(time);
          time += 28800000;
        }
        //反向
        timeArr = timeArr.sort((a, b) => {
          return b - a;
        });
        //转成年月日时分秒格式
        timeArr = timeArr.map((item) => {
          return getTiming(item);
        });
        let timeList = timeArr.slice(-res.data.length);
        //处理数据
        for (let i = 0; i < res.data.length; i++) {
          if (i == 0) {
            res.data[i].context =
              '您的包裹已经送达至本人/家人，如有疑问可致电菜鸟驿站人员或菜鸟客服9519666';
            res.data[i].address =
              findRes.s_address.dataValues.area_name +
              findRes.s_address.dataValues.desc;
            res.data[i]['phone'] = findRes.s_address.dataValues.phone;
          }
          if (i == 1) {
            res.data[i].context =
              '您的包裹正在由菜鸟驿站上门派送中,如有问题可致电菜鸟驿站人员或菜鸟客服9519666';
          }
          res.data[i].time = timeList[i];
        }
        let lRes = await Logistics.update({
          where: {
            //用户id
            user_id: userRes.dataValues.id,
            //订单id
            order_id: data.order_id,
            //物流信息
            content: JSON.stringify(res.data),
          },
        });
        await Order.update(
          {
            logistics: lRes.dataValues.id,
            status: '3',
          },
          {
            where: { order_id: data.order_id },
          }
        );
        return res.data;
      }
    } else {
      //获取物流信息
      let logistics = await ctx.curl(
        'http://www.kuaidi.com/index-ajaxselectcourierinfo--.html'
      );
      let res = JSON.parse(logistics.data);
      //查找下单的用户

      // console.log(userRes);
      //查找订单信息
      const order = await Order.findOne({
        where: {
          order_id: data.order_id,
        },
        include: [
          {
            model: Address,
          },
        ],
      });

      const userRes = await User.findOne({
        where: {
          id: order.user_id,
        },
      });

      //格式化时间
      let time = Number(order.dataValues.order_time);
      let timeArr = [];
      for (let i = 0; i < 30; i++) {
        timeArr.push(time);
        time += 28800000;
      }
      timeArr = timeArr.sort((a, b) => {
        return b - a;
      });
      timeArr = timeArr.map((item) => {
        return getTiming(item);
      });
      let timeList = timeArr.slice(-res.data.length);
      //处理数据
      for (let i = 0; i < res.data.length; i++) {
        if (i == 0) {
          res.data[i].context =
            '您的包裹已经送达至本人/家人，如有疑问可致电菜鸟驿站人员或菜鸟客服9519666';
          res.data[i].address = order.s_address.dataValues.area_name
            ? order.s_address.dataValues.area_name
            : '' + order.s_address.dataValues.desc;
          res.data[i]['phone'] = order.s_address.dataValues.phone;
        }
        if (i == 1) {
          res.data[i].context =
            '您的包裹正在由菜鸟驿站上门派送中,如有问题可致电菜鸟驿站人员或菜鸟客服9519666';
        }
        res.data[i].time = timeList[i];
      }

      let lRes = await Logistics.create({
        //用户id
        user_id: userRes.dataValues.id,
        //订单id
        order_id: data.order_id,
        //物流信息
        content: JSON.stringify(res.data),
      });
      await Order.update(
        {
          logistics: lRes.dataValues.id,
          status: '3',
        },
        {
          where: { order_id: data.order_id },
        }
      );
      return res.data;
    }
  }
  //获取物流信息
  async getLogistics() {
    const { app, ctx } = this;
    const { Order, Address, Logistics, User } = app.model.Tables.Shop;
    const data = ctx.query;
    //获取token
    const token = ctx.get('authorization');
    //查看该订单是否有物流信息
    let isOrder = await Logistics.findOne({
      where: {
        order_id: data.order_id,
      },
    });
    if (isOrder) {
      let res = await Logistics.findOne({
        where: {
          order_id: data.order_id,
        },
      });
      return JSON.parse(res.content);
    } else {
      return '没有物流信息';
    }
  }

  /** 根据订单ID获取订单详情 */
  getOrderById(order_id) {
    const { Order } = this.app.model.Tables.Shop;

    return Order.findOne({
      where: { order_id },
    });
  }

  async pay() {
    const { ctx, app } = this;
    const { Order, User } = app.model.Tables.Shop;
    const data = ctx.request.body;
    const userInfo = ctx.userInfo;
    const userMoney = userInfo.money || 0;

    const order = await Order.findByPk(data.id);
    if (!order) return [null, '订单不存在'];
    if (order.total_price > userMoney) return [null, '余额不足'];

    // 先将用户余额减去订单金额
    const user = await User.findByPk(userInfo.id);
    await user.update({
      money: userMoney - order.total_price,
    });

    try {
      // 再将订单状态改为已支付
      const result = await order.update(
        {
          status: '1',
        },
        {
          where: {
            id: data.id,
          },
        }
      );

      return [result, null];
    } catch (error) {
      return [null, error.message];
    }
  }
}

module.exports = AdminService;
